<template>
  <div class="ta-page">
    <div class="head">
      <svg-icon icon-class="user" /></span>
      <span>个人信息</span>
    </div>
    <div class="body">
      <!-- 用户账户 -->
      <div class="ta-page__info-item">
        <label>用户账户：</label>
        <template v-if="!showModifyAccount">
          <span style="margin-right: 15px">{{ username }}</span>
          <el-button size="small" @click="showModifyAccount = true">修改</el-button>
        </template>
        <template v-else>
          <el-input  size="small" style="width:120px;margin-right:15px" v-model="_name"></el-input>
          <el-button size="small" @click="showModifyAccount = false">取消</el-button>
          <el-button size="small" :loading="accountModifying" type="primary" @click="modifyAccount()">保存</el-button>
        </template>
      </div>

      <!-- 用户头像 -->
      <div class="ta-page__info-item">
        <label>用户头像：</label>
        <i-upload :cover="avatar" @success="getAvatar($event)"></i-upload>
      </div>

      <!-- 修改密码 -->
      <div class="ta-page__info-item">
        <label>登录密码：</label>
        <el-button v-if="!showForm" size="small" @click="showForm = true">修改密码</el-button>
        <div v-else class="ta-page__form-container">
          <el-form  class="ta-page__form" :rules="pwdRules" :model="pwd" ref="pwd">
            <el-form-item prop="oldPasswd">
              <el-input type="password"size="small"  v-model="pwd.oldPasswd" placeholder="请输入原密码"></el-input>
            </el-form-item>
            <el-form-item prop="newPasswd">
              <el-input type="password"size="small"  v-model="pwd.newPasswd" placeholder="请输入密码"></el-input>
            </el-form-item>
            <el-form-item prop="newPasswdConfirm">
              <el-input type="password" size="small" v-model="pwd.newPasswdConfirm" placeholder="请再次输入密码"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button size="small" @click="resetForm('pwd')">取消</el-button>
              <el-button size="small" type="primary" :loading="loading" @click="submitForm('pwd')">确认</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <!-- 用户角色 -->
      <div class="ta-page__info-item">
        <label>用户角色：</label>
        <span>{{ roles.join('、') }}</span>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import iUpload from 'base/Upload'
import md5 from 'js-md5'
export default {
  name: 'layout',
  data() {
    var newPasswd = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (value.length < 5 || value.length > 16) {
          callback(new Error('密码长度应在5到16之间'))
        }
        if (this.pwd.newPasswdConfirm !== '') {
          this.$refs.pwd.validateField('newPasswdConfirm')
        }
        callback()
      }
    }
    var newPasswdConfirm = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.pwd.newPasswd) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      // 修改账户
      showModifyAccount: false,
      accountModifying: false,
      // 修改头像
      uploadToken: '',
      // 修改密码
      loading: false,
      showForm: false,
      _name: '',
      pwd: {
        oldPasswd: '',
        newPasswd: '',
        newPasswdConfirm: ''
      },
      pwdRules: {
        oldPasswd: [
          { required: true, message: '密码不得为空', trigger: 'blur' }
        ],
        newPasswd: [
          { validator: newPasswd, trigger: 'blur' }
        ],
        newPasswdConfirm: [
          { validator: newPasswdConfirm, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'userId',
      'avatar',
      'roles',
      'username',
      'others'
    ])
  },
  created() {
    // this.$store.dispatch('GetQiniuToken')
    this._name = this.username
  },
  components: { iUpload },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          const info = {
            id: this.userId,
            old_pwd: md5(this.pwd.oldPasswd),
            new_pwd: md5(this.pwd.newPasswd),
            type: 'pwd'
          }
          try {
            const res = await this.$store.dispatch('UpdateUserMyself', info)
            if (res && res.code === 0) {
              await this.$store.dispatch('LogOut')
              this.$notify.success('密码修改成功，请重新登录')
              setTimeout(() => {
                location.reload()
              }, 200)
            }
          } catch (err) {
            console.log(err.message)
            this.$message.error(err.message)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.showForm = false
    },
    // 修改账户
    async modifyAccount() {
      if (this._name === this.username) {
        this.$message.info('未进行修改')
        this.accountModifying = false
        return
      }
      this.accountModifying = true
      const info = {
        id: this.userId,
        username: this._name,
        type: 'username'
      }
      try {
        await this.$store.dispatch('UpdateUserMyself', info)
        this.$store.commit('SET_USER_NAME', this._name)
        this.$notify.success('修改成功，再次登录请用新用户名')
        this.showModifyAccount = false
      } catch (err) {
        this.$message.error(err.message)
      } finally {
        this.accountModifying = false
      }
    },
    // 上传新头像
    async getAvatar(avatar) {
      const info = {
        id: this.userId,
        old_avatar: this.avatar,
        avatar,
        type: 'avatar'
      }
      this.$store.commit('SET_AVATAR', avatar)
      try {
        await this.$store.dispatch('UpdateUserMyself', info)
        this.$notify.success('头像已更新')
      } catch (err) {
        this.$message.error(err.message)
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.ta-page {
  max-width: 900px;
  border: 1px solid #e9eaec;
  border-radius: 5px;
  margin: 12px auto 0;
  text-align: center;
  background: #fff;
  .head {
    padding: 15px;
    border-bottom: 1px solid #e9eaec;
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }
  .body {
    padding: 25px;
    padding-top: 0;
    .ta-page__info-item {
      padding: 22px 0;
      border-top: 1px solid #e9eaec;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      label {
        display: inline-block;
        margin-right: 10px;
        color: #888;
        font-weight: normal;
      }
      &:first-of-type {
        margin-top: 0;
        border: 0;
      }
    }
  }
}
</style>
